package com.golxen.framework.common.server.agent;


import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.common.queue.AutoMQ;
import com.golxen.framework.common.queue.PlayerMQ;
import com.golxen.framework.executor.ThreadPlugin;
import com.golxen.framework.netty.session.agent.AgentChannel;
import com.golxen.framework.netty.websocket.AgentWebSocketServer;
import com.golxen.utils.LogUtil;
import io.netty.channel.Channel;

public class AgentPlayer implements PlayerMQ {

	private final long userId;

	private AgentChannel myChannel;

	public AgentPlayer(final long userId, Channel channel) {
		this.userId = userId;
		channel.attr(AgentWebSocketServer.CLIENT_KEY).set(userId);
		myChannel = new AgentChannel(channel);
	}


	public void setChannel(Channel channel) {
		channel.attr(AgentWebSocketServer.CLIENT_KEY).set(userId);
		myChannel = new AgentChannel(channel);
	}

	public long getUserId() {
		return userId;
	}

	public void send(PBPacket message) {
		if (myChannel != null) {
			myChannel.write(message);
		}
	}

	public void closeChannel() {
		LogUtil.COMMON.debug(" idle time out call closeChannel cid={} userId={}", myChannel.channel.id().asShortText(),
				userId);
		if (myChannel != null) {
			LogUtil.COMMON.debug(" idle time out call closeMyChannel cid={} userId={}",
					myChannel.channel.id().asShortText(), userId);
			myChannel.close();
		}
	}

	public AgentChannel getMyChannel() {
		return myChannel;
	}

	public Channel getChannel() {
		if (myChannel != null) {
			return myChannel.getChannel();
		}
		return null;
	}

	@Override
	public String toString() {
		StringBuilder msg = new StringBuilder();
		msg.append(userId).append("_").append(myChannel.hashCode());

		return msg.toString();
	}

	private final AutoMQ<Runnable> cmdQueue = new AutoMQ<Runnable>(ThreadPlugin.getServerCommandExecutor());

	public AutoMQ<Runnable> getCommandQueue() {
		return cmdQueue;
	}
}
